package com.belf.common.utils;


import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static com.belf.common.constant.Constants.HTTP_CONNECTION_TIMEOUT;
import static com.belf.common.constant.Constants.HTTP_SOCKET_TIMEOUT;


public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class.getName());
    /**
     * 发送POST请求，通过Body传递JSON格式的参数
     *
     * @param url      请求的URL
     * @param jsonBody 要发送的JSON字符串
     * @return 响应体内容
     * @throws IOException 如果发生IO异常
     */
    public static String postJson(String url, String jsonBody) throws IOException {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(HTTP_CONNECTION_TIMEOUT)
                    .setSocketTimeout(HTTP_SOCKET_TIMEOUT).build();

            httpPost.setConfig(requestConfig);
            // 创建HttpEntity实例，并设置请求体
            StringEntity entity = new StringEntity(jsonBody, "UTF-8");
            httpPost.setEntity(entity);


            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    logger.info("http status:{}", response.getStatusLine().getStatusCode());
                    // 获取响应体
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        // 返回响应体内容
                        return EntityUtils.toString(responseEntity, "UTF-8");
                    }
                }
            } catch (Exception e) {
                logger.error("http error:", e);
            }
        } catch (Exception e) {
            logger.error("http  error:", e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("http  client close error:", e);
            }
        }
        // 如果没有返回响应体，则返回null或抛出异常（根据需要处理）
        return null;
    }

    public static void main(String[] args) {
        String url = "http://example.com/api/endpoint";
        String jsonBody = "{\"key\":\"value\"}";

        try {
            String response = postJson(url, jsonBody);
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}